package com.woniuxy.cloud.carl.carlgoods.app.apiImpl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.cloud.carl.carlgoods.client.SpupropClient;
import com.woniuxy.cloud.carl.carlgoods.client.dto.SpuPropDto;
import com.woniuxy.cloud.carl.carlgoods.client.param.AddSpupropParam;
import com.woniuxy.cloud.carl.carlgoods.common.CarlgoodsResultCode;
import com.woniuxy.cloud.carl.carlgoods.infra.mapper.SpuMapper;
import com.woniuxy.cloud.carl.carlgoods.infra.mapper.SpuPropMapper;
import com.woniuxy.cloud.carl.carlgoods.infra.model.Spu;
import com.woniuxy.cloud.carl.carlgoods.infra.model.SpuProp;
import com.woniuxy.exceptions.MallException;
import com.woniuxy.result.Result;
import com.woniuxy.utils.Assert;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RestController
@Slf4j
@CrossOrigin("*")
public class SpupropImpl implements SpupropClient {
    @Resource
    private SpuMapper spuMapper;
    @Resource
    private SpuPropMapper spuPropMapper;
    @Override
    public Result addSpuprop(AddSpupropParam param) {
        Spu spu = spuMapper.selectById(param.getSpuId());
//        if(spu==null){
//            throw new MallException("该种商品不存在");
//        }
        Assert.state(spu!=null,"该种商品不存在");
        QueryWrapper<SpuProp> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("spu_id",param.getSpuId());
        queryWrapper.eq("prop_name",param.getPropName());
        SpuProp spuProp1 = spuPropMapper.selectOne(queryWrapper);
      if(spuProp1!=null){
          throw new MallException(CarlgoodsResultCode.DATA_NOT_DOUBLE);
      }
        SpuProp spuProp = BeanUtil.toBean(param, SpuProp.class);
        spuPropMapper.insert(spuProp);
        return Result.success();
    }

    @Override
    public Result<List<SpuPropDto>> list() {
        List<SpuProp> spuProps = spuPropMapper.selectList(null);
        List<SpuPropDto> spuPropDtos = BeanUtil.copyToList(spuProps, SpuPropDto.class);
        for (SpuPropDto spuPropDto : spuPropDtos) {
            Long spuId = spuPropDto.getSpuId();
            Spu spu = spuMapper.selectById(spuId);
            spuPropDto.setSpuName(spu.getSpuName());

        }
        return Result.success(spuPropDtos);
    }
}
